package dao

import (
	"dc-news-admin-api/common/utils"
	"dc-news-admin-api/entity"
	"errors"
	"github.com/spf13/cast"
	"go.uber.org/zap"
	"gorm.io/gorm"
)

// GetAdminByUsername 通过用户名获取管理员用户
func GetAdminByUsername(username string) (admin *entity.Admin, err error) {
	admin = new(entity.Admin)
	err = DB.
		Model(&entity.Admin{}).
		Where("username = ?", username).
		First(admin).
		Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return nil, nil
		} else {
			zap.S().Error("通过用户名获取用户操作数据库错误: ", err)
			return nil, err
		}
	}
	return
}

func CreateAdmin(admin *entity.Admin) (err error) {
	err = DB.Create(admin).Error
	return
}

func ModifyAdminRoleById(id int, role string) (err error) {
	err = DB.
		Model(&entity.Admin{}).
		Where("id = ?", id).
		Updates(&entity.Admin{Role: role}).
		Error
	return
}

func UpdateAdminPasswordById(id int, password string) (err error) {
	value := map[string]interface{}{
		"password":  password,
		"is_active": false,
	}
	err = DB.
		Model(&entity.Admin{}).
		Where("id = ?", id).
		Updates(value).
		Error
	return
}

func DeleteAdminById(id int) (err error) {
	err = DB.
		Model(&entity.Admin{}).
		Where("id = ?", id).
		Delete(&entity.Admin{}).
		Error
	return
}

func GetAdminListByPage(p *utils.Pagination) (admins []entity.Admin, err error) {
	admins = make([]entity.Admin, 0)
	err = DB.Model(&entity.Admin{}).Scopes(p.GormPaginate()).Find(&admins).Error
	if err != nil {
		return
	}
	var count int64
	DB.Model(&entity.Admin{}).Count(&count)
	p.Total = cast.ToInt(count)
	return
}
